#include "common.h"

/*******************************************************************************
* 去抖动信号
* debouncing_signal_init(). 初始化信号
* debouncing_signal_in(). 信号输入
*
*******************************************************************************/


void debouncing_signal_init(debouncing_signal_t *signal, uint16_t interval, uint8_t initial_value)
{
    signal->interval = interval;
    signal->status = kDebSignal_StatusStable;
    signal->current_value = initial_value;
    signal->cnt = 0;
}

uint8_t debouncing_signal_in(debouncing_signal_t *signal, uint16_t tick, uint8_t s_in)
{
    if(signal->status==kDebSignal_StatusStable) {//信号稳定期间
        if(s_in!=signal->current_value) {
            signal->status = kDebSignal_StatusShake;
            signal->cnt = 0;
        }
    }
    else {   
        signal->cnt += tick;
        if(signal->cnt>=signal->interval) {
            signal->current_value = s_in;
        }
    }
    return signal->current_value;
}

uint8_t check8BitSum(uint8_t *p_dat, uint16_t len) {
    uint8_t sum = 0;
    while (len-- > 0) { // 有数据未校验
        sum += *p_dat++; // 求取模算术和
    }
    return sum; // 返回校验和
}


void ring_buffer_init(ring_buffer_t *buffer, uint8_t *buff, uint16_t size)
{
    buffer->buff = buff;
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->status = kRingBuffer_status_empty;
}

void ring_buffer_write(ring_buffer_t *buffer, uint8_t data)
{
    buffer->buff[buffer->tail++] = data;
    if(buffer->tail==buffer->size)
        buffer->tail = 0;
    buffer->status = kRingBuffer_status_normal;
}
/*!
 * brief Get the length of received data in ring buffer.
 *
 * param handle ring buffer pointer.
 * return Length of received data in ring buffer.
 */
uint32_t ring_buffer_get_length(ring_buffer_t *buffer)
{
    uint16_t length;
    uint32_t head = buffer->head;
    uint32_t tail = buffer->tail;
    if (tail < head)
        length = tail + buffer->size - head;
    else
        length = tail - head;
    return length;
}

uint32_t ring_buff_read(ring_buffer_t *buffer, uint8_t *read_buffer, uint16_t read_size)
{
    uint16_t i;
    uint16_t length;
    length = ring_buffer_get_length(buffer);
    length = MIN(length,length);
    for(i=0;i!=length;i++) {
        *read_buffer++ = buffer->buff[buffer->head];
        if(buffer->head+1==buffer->size)
            buffer->head = 0;
        else
            buffer->head++;
    }
    return length;
}
